<template>
  <div class="food-info-container">
    <h1>食品详情</h1>
    <div class="food-info">
      <div class="img_box">
        <img :src="foodInfo.foodImageUrl" alt="Food Image" />
      </div>
      <div class="details">
        <h2>{{ foodInfo.foodName }}</h2>
        <p>价格: &yen;{{ foodInfo.foodPrice }}</p>
        <p>到期时间: {{ foodInfo.expiryDate }}</p>
        <p>描述: {{ foodInfo.foodDescription }}</p>
        <p>剩余数量: {{ foodInfo.stockQuantity }}</p>
        <p>店铺名称: {{ foodInfo.sellerName }}</p>

        <div class="purchase-section">
          <label prop="quantity">购买数量:</label>
          <input
              type="number"
              v-model="quantity"
              min="1"
              :max="foodInfo.stockQuantity"
              @input="quantity = Math.min(quantity, foodInfo.stockQuantity)"
          />
          <button @click="purchase" :disabled="loading">
            {{ loading ? '正在购买...' : '购买' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { foodInfoService, addOrderService } from "@/api/food";

export default {
  setup() {
    const route = useRoute();
    const foodId = ref(route.query.foodId);
    const foodInfo = ref({});
    const quantity = ref(1);
    const loading = ref(false);

    const orderModel = ref({
      foodId: foodId.value,
      quantity: '',
    });

    onMounted(async () => {
      try {
        const response = await foodInfoService(foodId.value);
        foodInfo.value = response.data;
      } catch (error) {
        console.error('Failed to fetch foodInfo:', error);
      }
    });

    const purchase = async () => {
      if (quantity.value > foodInfo.value.stockQuantity) {
        alert('库存不足');
      } else {
        loading.value = true;
        orderModel.value.foodId = foodId.value;
        orderModel.value.quantity = quantity.value;

        try {
          const response = await addOrderService(orderModel.value);
          alert(response.msg || '购买成功');
        } catch (error) {
          console.error('购买失败:', error);
          alert('购买失败，请重试');
        } finally {
          loading.value = false;
        }
      }
    };

    return { foodInfo, quantity, purchase, loading };
  }
};
</script>

<style scoped>
.food-info-container {
  padding: 20px;
}

.food-info {
  display: flex;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 10px;
  background: #f9f9f9;
}

.img_box {
  margin-right: 20px;
}

.img_box img {
  width: 150px;
  height: 150px;
  border-radius: 8px;
}

.details {
  flex-grow: 1;
}

.details h2 {
  margin: 0;
  font-size: 20px;
}

.details p {
  margin: 5px 0;
}

.purchase-section {
  margin-top: 15px;
}

.purchase-section input {
  width: 50px;
  margin-right: 10px;
}
</style>
